const Route = loader("Route");
//解析路由
exports.start=init;
function init(){
    //全局路由对象
    global.route = {};
    global.router = {};
    //运行时路由存储
    global.runRoute = {};
    //运行时路由存储
    global.runRouter = {};
  //读取配置属性中的路由文件
  global.gem_config.routeConfig.forEach(({file,prefix="",midd})=>{
    //运行路由文件
    run_rout(file,prefix,midd);
  });


}

exports.run_rout=run_rout;
//运行一个路由文件
function run_rout(file,prefix,midd){
  //解析全局中间件
  global.route.globalRouter = loader('global_midd',true)();
  //初始化路由
  Route.init({
    //文件名称   文件级前缀
    filepath:file, file_prefix:prefix==="/"?"":prefix,
    //文件级中间件
    file_midd:midd?midd:[],
  });
  //执行路由文件
  try{
    loader(process.cwd()+file,true)();
    //合并文件的内容
    mergeRout();
  }catch(e){
    console.log(file,"模块出现问题，请修复后运行\n"+e);
    console.log(e);
  }
}

//合并路由文件
exports.mergeRout = mergeRout;
function mergeRout (){
  global.route = Object_merge(global.runRoute);
  global.router = Object_merge(global.runRouter);
}


//合并两个对象，内容相同合并，不同则添加
function Object_merge(objarr){
  if(!Array.isArray(objarr)){objarr = Object.keys(objarr).map(e=>objarr[e])}
  let obj = {};
  objarr.forEach(d=>{
    Object.keys(d).forEach(e=>{
      if(obj[e]){
        let type_d =Array.isArray(d[e])?"array":typeof d[e];
        let type_obj =Array.isArray(obj[e])?"array":typeof obj[e];
        //对象存在,判断类型
        if(type_d==='array' && type_obj === 'array'){
          //都是数组，合并
          obj[e] = obj[e].concat(d[e]);
        }else if(type_d === 'object' && type_obj === 'object'){
          //都是对象就迭代
          obj[e] = Object_merge([obj[e],d[e]]);
        }else if(["array","object"].includes(type_d) && ["array","object"].includes(type_obj)){
          //肯定是一个对象，一个数组
          obj[e] = Object_merge([{...obj[e]},{...d[e]}]);
        }else if(["array","object"].includes(type_d) || ["array","object"].includes(type_obj)){
          let a,b;
          //其中有一个对象或数组，另外一个是基本数据类型
          ["array","object"].includes(type_obj)?(a=obj[e],b=d[e]):(a=d[e],b=obj[e]);
          if(Array.isArray(a)){obj[e] = a,a.push(b)}else{
            obj[e] = {...a,[b]:b}
          }
        }else{
          //两者都是基本数据类型或者是方法
          console.log([type_obj,type_d])
          obj[e] = [obj[e],d[e]];
        }
      }else{
        //对象不存在
        obj[e]=d[e];
      }
    })
  })
  return obj;
}